package com.hspedu.newData.dmsxl.哈希表;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-04-29 
 * @Version: 1.0
 */

public class LC15三数之和 {

    // todo
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        for (int first = 0; first < n; first++) {

            if (first > 0 && nums[first] == nums[first-1]){
                continue;
            }
            int third = n - 1;
            int target = -nums[first];

            for (int second = first + 1; second < n; second++) {
                if (second > first+1 && nums[second] == nums[second-1]){
                    continue;
                }

                while(second < third && nums[second] + nums[third]> target){
                    --third;
                }

                if (second == third){
                    break;
                }

                if (nums[second] + nums[third] == target){

                    List<Integer> list = new ArrayList<>();
                    list.add(nums[first]);
                    list.add(nums[second]);
                    list.add(nums[third]);
                    res.add(list);
                }
            }
        }
        return res;

    }
}
